module dwt.util.hashtable;


int foo;

class Hashtable(K, V) {
	
	private import dwt.dwt;
	
	// for performance reason, we rehash the array every time 
	// the growth reach the predefined REHASH_THRESHOLD,
	private int counterMon = 0; // monitor the length changing of hash table 
	private int _REHASH_THRESHOLD = 256;

	debug{
		static int count = 0;
		void instCreate(){
//		Util.trace("Total Hashtable!(%s, %s) count, %4d, constructor", typeid(K).toString(), typeid(V).toString(), ++count);
		}
		void instDestroy(){
//		Util.trace("Total Hashtable!(%s, %s) count, %4d, destructor", typeid(K).toString(), typeid(V).toString(), --count);
		}
	}
	
	private V[K] _values;
	
	public this() {
		debug{instCreate();}
	}	
	
	public ~this() {
		debug{instDestroy();}
		clear();
	}
	
	public int length(){
		return _values.length;
	}
	alias length getSize;
	
	public V get(K key){
		if(contains(key))
			return _values[key];
		// return null or "0"
		return cast(V)cast(void*)null;
	}
	
	public boolean contains(K key){
		return ((key in _values) !is null);
	}
	
	public void put(K key, V value){
		_values[key] = value;
		rehashCheck();
	}
	
	
	public V remove(K key){
		if(contains(key)){
			V obj = _values[key];
			_values.remove(key);
			rehashCheck();
			return obj;
		}else{
			// return null or "0"
			return cast(V)cast(void*)null;
		}
		
	}
	
	public void clear(){
		_values = null;		
	}

	public int REHASH_THRESHOLD() { return _REHASH_THRESHOLD;}

	// don't set rehash threshold too small
	public void REHASH_THRESHOLD(int value) { 
		if(value >= 64)
			_REHASH_THRESHOLD = value;
	}

	private void rehashCheck(){
		int count = length() / _REHASH_THRESHOLD;
		if(count != counterMon){
			counterMon = count;
			_values.rehash;
		}
	}

	// force rehash
	public void rehash() { _values.rehash; }

	public K[] keys() {return _values.keys;}
	public V[] values(){ return _values.values;}
	public alias values elements;
	
}